<?php


namespace app\common\business;

//逻辑处理层
use app\admin\model\SpecGoods;
use app\common\model\Attribute;
use app\common\model\Goods;
use app\common\model\GoodsImages;
use app\common\model\Spec;
use app\common\model\SpecValue;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Db;

class Type
{
    /**
     * 商品的添加
     * @param $data
     * @return \think\response\Json
     */
     public static function Add($data){
         $attr=[];
         foreach ($data['attr'] as $val){
             $attr[]=$val;
         }
         //d($attr);
         //处理分割
         $goods=[
             'goods_name'=>$data['goods_name'],
             'goods_price'=>$data['goods_price'],
             'goods_desc'=>$data['goods_introduce'],
             'goods_logo'=>$data['goods_logo'],
             'cate_id'=>$data['cate_id'],
             'brand_id'=>$data['brand_id'],
             'type_id'=>$data['type_id'],
             'goods_attr'=>json_encode($attr)
         ];
         // 启动事务
         Db::startTrans();
         try {
             //分开添加三个表，商品表，商品图片表，商品与规格表
             //第一张
             $goodsModel=new \app\common\model\Goods();
             $res= $goodsModel->save($goods);
             //(`goods_id`, `value_ids`, `value_names`, `price`, `cost_price`, `store_count`, `store_frozen`
             $goods_id=$goodsModel->id;//这种有效，那种getlastinsertid不行




             $spec_goods=[];
             foreach ($data['item'] as $val){
                 $val['goods_id']=$goods_id;
                 $spec_goods[]=$val;
             }
             //批量添加第二张表
             $obj=new SpecGoods();
             $obj->saveAll($spec_goods);



             //批量添加第三张表
             $files=$data['goods_images'];
//            $pics_big=[];
//            $pics_sma=[];
             $goods_imgs=[];
             //dd($files);
             foreach ($files as $k=>$file){//多文件上传写在循环里
                 //验证文件大小和类型
                 try {
                     validate(['image'=>[
                         'fileExt'=>'jpg,jpeg,gif,png',
                         'fileSize'=>'2097152'
                     ]])->check(['image'=>$file]);
                     $image = \think\Image::open($file);
                     //随机生成文件名
                     //pathinfo(),里面面跟着路径
                     $extension=pathinfo($file->getOriginalName())['extension'];
                     $fileName1='800_'.md5($k.time().uniqid('123')).'.'.$extension;
                     $fileName2='400_'.md5($k.time().uniqid('123')).'.'.$extension;
                     //方法二
//                    $fileName1=md5($k.'800*800'.date('Ymd His').'.png');
//                    $fileName2=md5($k.'400*400'.date('Ymd His').'.png');
                     $image->thumb(800,800,\think\Image::THUMB_SOUTHEAST)->save('./img/big/'.$fileName1);
                     $image->thumb(400,400,\think\Image::THUMB_SOUTHEAST)->save('./img/small/'.$fileName2);

                     $goods_imgs[]=[
                         'goods_id'=>$goods_id,
                         'pics_big'=>'./img/big/'.$fileName1.'.png',
                         'pics_sma'=>'./img/small/'.$fileName2.'.png'
                     ];
                     $error[]='';
                 }catch (ValidateException $e){
                     $error[]=['name'=>$file->getOriginalName(),'msg'=>$e->getMessage()];
                 }
             }
             $GoodsImages=new GoodsImages();
             $GoodsImages->saveAll($goods_imgs);
             // 提交事务
             Db::commit();
             return  successes('添加成功');
         } catch (\Exception $e) {
             // 回滚事务
             Db::rollback();
             return fail($e->getMessage());
         }

     }


    /**
     * 商品类型的删除
     * @param $id
     * @return \think\response\Json
     */
     public static function delete($id){
         //多表操作一定要开启事务
         Db::startTrans();
         try{
             //四个表挨个删除
             \app\common\model\Type::destroy($id);
             Attribute::where('type_id',$id)->select()->delete();//一定要先查出来，才能删除
             Spec::where('type_id',$id)->select()->delete();
             SpecValue::where('type_id',$id)->select()->delete();
             Db::commit();
             return successes('删除成功');
         }catch(DbException $e){
             Db::rollback();
             return fail($e->getMessage());
         }
     }




    /**
     * 商品删除
     * @param $id
     * @return \think\response\Json
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function GoodsDel($id){
         $goods=Goods::find($id);
         if($goods['is_on_sale']==1){
             return fail('商品正在上架中，不能删除');
         }
//执行多表删除
        //事务
        Db::startTrans();
        try{
            //商品表，spec—goods，goods_images,
            $res1=Goods::destroy($id);
            $res2=GoodsImages::where('goods_id',$id)->select()->delete();
            SpecGoods::where('goods_id',$id)->select()->delete();
            Db::commit();
            return successes('删除成功');
        }catch(DbException $e){
            Db::rollback();
            return fail($e->getMessage());
        }
    }

    //商品修改
    public static function GoodsUpdate($id,$data){

        $res=Goods::find($id);
        if(!$res){
            return fail('该商品不存在');
        }
        //三表修改
        //添加新的规格商品SKU
        $attr=[];
        foreach ($data['attr'] as $val){
            $attr[]=$val;
        }
        //d($attr);
        //处理分割
        $goods=[
            'goods_name'=>$data['goods_name'],
            'goods_price'=>$data['goods_price'],
            'goods_desc'=>$data['goods_introduce'],
            'goods_logo'=>$data['goods_logo'],
            'cate_id'=>$data['cate_id'],
            'brand_id'=>$data['brand_id'],
            'type_id'=>$data['type_id'],
            'goods_attr'=>json_encode($attr)
        ];
        // 启动事务
        Db::startTrans();
        try {
            //分开更新三个表，商品表，商品图片表，商品与规格表
            //第一张
            $goodsModel=new \app\common\model\Goods();
            $res= $goodsModel->where('id',$id)->save($goods);
            //(`goods_id`, `value_ids`, `value_names`, `price`, `cost_price`, `store_count`, `store_frozen`
            //$goods_id=$goodsModel->id;//这种有效，那种getlastinsertid不行




            $spec_goods=[];
            foreach ($data['item'] as $val){
                $val['goods_id']=$id;
                $spec_goods[]=$val;
            }
            //批量添加第二张表
            //同一个goods——id下的规格值不能重复，即value——IDS不能重复
            //dd($spec_goods);

            //查出某个商品下对应的value_ids
//            $result=Goods::with('specGoods')->find($id)->toArray();
//           // dd($result);
//            $spec_goods_ids=[];
//            foreach ($result['specGoods'] as $val){
//                $spec_goods_ids[]=$val['id'];
//            }
//            //接到对应的第二张表主键id，然后修改
//            $ids=['885','886','887','888'];
            //$spec_goods_id=885;
            $obj=new SpecGoods();
            foreach ($spec_goods as $v){
                $obj->where('id',$v['id'])->save($v);
            }


            //批量添加第三张表

            //接到原来图片的储存id位置
            $img_id=277;


            $files=$data['goods_images'];
//            $pics_big=[];
//            $pics_sma=[];
            $goods_imgs=[];
            //dd($files);
            foreach ($files as $k=>$file){//多文件上传写在循环里
                //验证文件大小和类型
                try {
                    validate(['image'=>[
                        'fileExt'=>'jpg,jpeg,gif,png',
                        'fileSize'=>'2097152'
                    ]])->check(['image'=>$file]);
                    $image = \think\Image::open($file);
                    //随机生成文件名
                    //pathinfo(),里面面跟着路径
                    $extension=pathinfo($file->getOriginalName())['extension'];
                    $fileName1='800_'.md5($k.time().uniqid('123')).'.'.$extension;
                    $fileName2='400_'.md5($k.time().uniqid('123')).'.'.$extension;
                    //方法二
//                    $fileName1=md5($k.'800*800'.date('Ymd His').'.png');
//                    $fileName2=md5($k.'400*400'.date('Ymd His').'.png');
                    $image->thumb(800,800,\think\Image::THUMB_SOUTHEAST)->save('./img/big/'.$fileName1);
                    $image->thumb(400,400,\think\Image::THUMB_SOUTHEAST)->save('./img/small/'.$fileName2);

                    $goods_imgs[]=[
                        'id'=>'277',
                        'goods_id'=>$id,
                        'pics_big'=>'./img/big/'.$fileName1,
                        'pics_sma'=>'./img/small/'.$fileName2
                    ];
                    $error[]='';
                }catch (ValidateException $e){
                    $error[]=['name'=>$file->getOriginalName(),'msg'=>$e->getMessage()];
                }
            }
            $GoodsImages=new GoodsImages();
           // dd($goods_imgs);
            foreach ($goods_imgs as $v){
                $GoodsImages->where('id',$v['id'])->save($v);
            }

            // 提交事务
            Db::commit();
            return  successes('修改成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return fail($e->getMessage());
        }

    }


    /**
     * 商品单条查询
     */
    public static function GoodsEdit($id){
        $res=Goods::find($id);
        if(!$res){
            return fail('该商品不存在');
        }
        //goods,cate,type三表关联查询，返回数据
        $data=Goods::where('id',$id)->with(['brands','cate', 'specGoods','Types','images'])
            ->hidden(['brands'=>['create_time','update_time','delete_time'],'cate'=>['create_time','update_time','delete_time']])
            ->paginate(3)->toArray();
         if($data['data']){
             return successes('查询成功',$data);
         }else{
             return fail('查询失败');
         }


    }

}